 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LosScrum.Models;
using System.Web.Script.Serialization;
using System.Text;
using System.Net;
using System.IO;

namespace LosScrum.Controllers
{
    public class MaterialController : Controller
    {
        private string materialRESTService = "http://localhost:33348/Materiales.svc/Materiales";
        JavaScriptSerializer js = new JavaScriptSerializer();

        

        private List<Material> CrearMateriales()
        {
            List<Material> materiales = new List<Material>();

            materiales.Add(new Material() { Codigo = 1, Nombre = "MOTA", Estado = "A" });
            materiales.Add(new Material() { Codigo = 2, Nombre = "PLUMON AZUL", Estado = "A" });
            materiales.Add(new Material() { Codigo = 3, Nombre = "PIZARRA", Estado = "A" });
            materiales.Add(new Material() { Codigo = 4, Nombre = "PLUMON ROJO", Estado = "A" });


            return materiales;
        }

        private Material ObtenerMateriales(int codigo)
        {
            List<Material> materiales = (List<Material>)Session["materiales"];

            Material model = materiales.Single(delegate(Material material)
            {
                if (material.Codigo == codigo) return true;
                else return false;
            });
            return model;
        }

        //
        // GET: /Recursos/

        public ActionResult Index()
        {
            //if (Session["materiales"] == null)
            //    Session["materiales"] = CrearMateriales();
            //List<Material> model = (List<Material>)Session["materiales"];
            //return View(model);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string materialesJson = reader.ReadToEnd();
            List<Material> materiales = js.Deserialize<List<Material>>(materialesJson);
            return View(materiales);


        }

        //
        // GET: /Recursos/Details/5

        public ActionResult Details(int id)
        {
            //Material model = ObtenerMateriales(id);
            //return View(model);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService + "/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string materialJson = reader.ReadToEnd();
            Material material = js.Deserialize<Material>(materialJson);
            return View(material);
        }

        //
        // GET: /Recursos/Create

        public ActionResult Create()
        {
            return View();
        } 

        //
        // POST: /Recursos/Create

        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            //try
            //{
            //    List<Material> recursos = (List<Material>)Session["materiales"];
            //    recursos.Add(new Material()
            //    {
            //        Codigo = int.Parse(collection["Codigo"]),
            //        Nombre = collection["Nombre"],
            //        Estado = collection["Estado"],
            //    });

            //    return RedirectToAction("Index");
            //}
            //catch
            //{
            //    return View();
            //}

            try
            {
                string postdata = "{\"Codigo\":\"" + collection["Codigo"] + "\",\"Nombre\":\"" + collection["Nombre"] + "\",\"Estado\":\"" + collection["Estado"] + "\"}";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService);
                req.Method = "POST";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                //ModelState.AddModelError("Error", e.Message);
                //return View();


                TempData["message"] = "MATERIAL YA EXISTE!!!!!!!!!!!!!!!!!!!!!!!";
                return (RedirectToAction("Create"));
            }




        }
        
        //
        // GET: /Recursos/Edit/5
 
        public ActionResult Edit(int id)
        {
            //Material model = ObtenerMateriales(id);
            //return View(model);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService + "/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string materialJson = reader.ReadToEnd();
            Material material = js.Deserialize<Material>(materialJson);
            return View(material);
        }

        //
        // POST: /Recursos/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            //try
            //{
            //    Material model = ObtenerMateriales(id);
            //    model.Nombre= collection["Nombre"];
            //    model.Estado = collection["Estado"]; 
            //    return RedirectToAction("Index");
            //}
            //catch
            //{
            //    return View();
            //}


            try
            {
                string postdata = "{\"Codigo\":\"" + id + "\",\"Nombre\":\"" + collection["Nombre"] + "\"}";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService);
                req.Method = "PUT";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Recursos/Delete/5
 
        public ActionResult Delete(int id)
        {
            //Material model = ObtenerMateriales(id);
            //return View(model);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService + "/" + id);
            req.Method = "GET";
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            StreamReader reader = new StreamReader(res.GetResponseStream());
            string materialJson = reader.ReadToEnd();
            Material material = js.Deserialize<Material>(materialJson);
            return View(material);
        }

        //
        // POST: /Recursos/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            //try
            //{
            //    List<Material> materiales = (List<Material>)Session["materiales"];
            //    materiales.Remove(ObtenerMateriales(id));
            //    return RedirectToAction("Index");
            //}
            //catch
            //{
            //    return View();
            //}

            try
            {
                string postdata = "\"" + id + "\"";
                byte[] data = Encoding.UTF8.GetBytes(postdata);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(materialRESTService + "/" + id);
                req.Method = "DELETE";
                req.ContentLength = data.Length;
                req.ContentType = "application/json";
                var reqStream = req.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                var res = (HttpWebResponse)req.GetResponse();
                return RedirectToAction("Index");
            }
            catch (Exception e)
            {
                return View();
            }
        }
    }
}
